package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entity.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author early_morning
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-05-13 21:10:39
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    public static final String CACHE_KEY_USER = "user:";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void addUser(User user) {
        boolean resultValue = false;
        log.info("插入之前的user:{}",user);
        // 返回的是影响行数
        resultValue = save(user);
        log.info("插入之后的user:{}",user);
        if(resultValue) {
            // 到数据库查询用户的信息
            User userInfo = getById(user.getId());
            log.info("用户信息：{}",userInfo);
            // 设置key
            String userKey = CACHE_KEY_USER + user.getId();
            // 存储到 redis 中
            redisTemplate.opsForValue().set(userKey,userInfo);
        }
    }


    /**
     * 获取用户信息
     * @param id
     * @return
     */
    /*@Override
    public User getUserById(Long id) {
        User user = null;
        String userKey = CACHE_KEY_USER + id;
        user = (User) redisTemplate.opsForValue().get(userKey);
        if(user == null) {
            // 从数据库中查询
            user = getById(id);
            if(user != null) {
                // 从数据库中查到数据，存到 redis 中
                redisTemplate.opsForValue().set(userKey,user);
            }
        }
        return user;
    }*/

    /**
     * 会将返回值存进 redis，key生成规则需要程序员用SpEL表达式自己指定，value就是程序从mysql查出并返回user
     * redis的 key 等于  keyPrefix:matchValue
     * @param id
     * @return
     */
    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getUserById(Long id) {
        return getById(id);
    }
}




